<template>
    <view class="container">
        <!-- 订单状态导航 -->
        <view class="order-nav">
            <scroll-view scroll-x="true" class="scroll-view">
                <view class="nav-item"
                    v-for="item in orderStatus"
                    :key="item.value"
                    :class="{ active: currentStatus === item.value }"
                    @tap="switchStatus(item.value)">
                    {{ item.label }}
                </view>
            </scroll-view>
        </view>

        <!-- 订单列表 -->
        <view class="order-list" >
            <view class="order-item" v-for="(item, index) in orderList" :key="index" @tap="goDetail(item)">
                <view class="order_no" @click.stop="copyOrderNo(item.FOrderNo)"> 订单号：{{item.FOrderNo}} <text>复制</text> </view>
                <view class="order-header">
                    <view class="store-info">
                        <!-- <uni-icons type="shop" size="18"></uni-icons> -->
                        <!-- <text class="store-name">{{ item.storeName }}</text> -->
                        <text class="store-name">已还期数/总期数：{{item.planInfo.payed}}/{{item.planInfo.total}}</text>
                    </view>
                    <template v-if="item.FRentDebitStatus == '00'">
                        <text class="order-status" v-if="item.FOrderStatus == '01' && item.FPayedAmount > 0">已付款</text>
                        <text class="order-status" v-else-if="item.FOrderStatus == '01' && item.FPayedAmount == 0">待付款</text>
                        <text class="order-status" v-else>待签约</text>
                    </template>
                    <text class="order-status" v-if="item.FRentDebitStatus == '01'">租赁中</text>
                    <text class="order-status" v-if="item.FRentDebitStatus == '02'">已离开</text>
                    <text class="order-status" v-if="item.FRentDebitStatus == '04'">已结束</text>
                    <!-- <text class="order-status" v-if="item.FRentDebitStatus == '04'">已结束</text> -->
                </view>

                <view class="order-content">
                    <image class="product-img" :src="item.proInfo.FProImg || '/static/errorImage.jpg'" mode="aspectFill"></image>
                    <view class="order-info">
                        <view class="product-name">{{ item.proInfo.FProName }}</view>
                        <view class="product-specs">{{ item.proInfo.FPresPerNum }}期，每期{{item.proInfo.FPresPer}}天</view>
                        <view class="price-info">
                            <text class="count">每期租金：</text>
                            <text class="price">{{ item.proInfo.FSellPrice }} </text>
                        </view>
                        <!-- <view class="price-info">
                            <text class="count">认证费：</text>
                            <text class="count">{{ item.renZhenInfo.FSellPrice }} </text>
                            <text class="count">，押金：</text>
                            <text class="count">{{ item.proInfo.FSellPrice}}</text>
                        </view> -->


                    </view>
                </view>

                <view class="order-footer">
                    <view class="total flex-v-center" v-if="item.FPayedAmount">
                        <view>
                            <button class="yj_btn" v-if="item.FDepositAmount > 0 && isDev" @tap="toYajinList(item)">押金扣款记录</button>
                        </view>
                        <view class="flex-1"></view>
                        已付：
                        <text class="total-price">￥{{ item.FPayedAmount }}</text>
                    </view>
                    <!-- <view class="total" v-if="item.FPayedAmount">
                        已付：认证费
                        <text class="total-price">￥{{ item.FPayedAmount }}</text>
                        <template v-if="item.FDepostiStatus == '01'">
                            ，押金
                            <text v-if="item.FDepositSource == 'ali'" class="total-price">￥{{ item.FDepositAmount }}</text>
                            <text v-if="item.FDepositSource == 'ali-zmmy'" class="total-price">芝麻免押</text>
                        </template>
                    </view> -->
                    <view class="btn-group">
                        <div class="btn call_phone" @click.stop="showKefuWeixinDialog('')">联系客服</div>
                        <!-- <div class="btn call_phone" @click.stop="callService">联系客服</div> -->
                        <div class="flex-1"></div>
                        <button v-if="(item.FOrderStatus == '01' || item.FOrderStatus == '00') && item.FPayedAmount <= 0" class="btn btn-cancel" @click.stop="handleCancelOrder(item)">取消订单</button>
                        <button class="btn btn-primary" v-if="item.FRentDebitStatus == '00'" @click.stop="payOrder(item)">继续签约</button>

                        <div v-if="item.FRentDebitStatus == '01' && item.applyStatus != '00'" class="btn call_phone" @click.stop="applyFinish(item)">去退租</div>
                        <!-- applyStatus 00 申请中，01 申请通过 ，02 申请拒绝 -->
                        <p class="finish_remark" v-if="item.applyStatus == '00'">
                            退租申请中{{item.applyRemark ? '，' + item.applyRemark : ''}}
                            <!-- <span style="color: #409eff;" @click.stop="showKefuWeixinDialog()">联系客服</span> -->
                        </p>
                    </view>
                    <div style="color: red;margin-top: 10rpx;text-align: right;" v-if="item.checkRemark">审核：{{item.checkRemark}}</div>
                </view>
            </view>

            <uni-popup ref="kefuWeixinDialogRef" type="center">
                <view class="kefu_weixin_dialog">
                    <view class="title">{{kefuDialogTitle}}</view>
                    <view class="img">
                        <image :src="$store.state.shop.shopInfo.serviceQrCode"  mode="widthFix" show-menu-by-longpress />
                    </view>
                    <view @click="callKefuPhone" class="call_phone">
                        或拨打客服电话：
                        <text>
                            {{$store.state.shop.shopInfo.concatPhone}}
                        </text>
                    </view>
                </view>
            </uni-popup>

            <list-end :loading="listPager.loading" :max="listPager.max" :noData="listPager.noData"></list-end>
            <popup-edit ref="popupEditRef"></popup-edit>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref } from "vue"
import { onLoad, onShow, onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app"
import { getRentOrders, cancelOrder, applyFinishRent } from "@/api/order"
import { getNearStoreByDistance } from '@/api/shop';
import listEnd from "@/components/base/list-end.vue"
import popupEdit from '@/components/base/popup-edit.vue'

import interact from "@/utils/interact"
import { useStore } from "vuex";
const Store = useStore();

const isDev = ref(process.env.NODE_ENV == 'development')


// 订单状态列表
const orderStatus = ref([
    { label: '全部', value: '' },
    { label: '待支付', value: '01' },
    { label: '已付款', value: '02' },
    { label: '租赁中', value: '03' },
    { label: '已逾期', value: '04' },
    { label: '已到期', value: '05' },
    { label: '已结束', value: '06' },
    { label: '已取消', value: '99' },
])
const currentStatus = ref('')
// 切换订单状态
const switchStatus = (status: string) => {
    currentStatus.value = status
    onRefresh()
}

const concatPhone = ref('')
onLoad(() => {
    onRefresh()
    concatPhone.value = Store.state.shop.shopInfo.concatPhone
})

onPullDownRefresh(() => {
    onRefresh(() => {
        uni.stopPullDownRefresh()
    })
})

onReachBottom(() => {
    onInfinite()
})

const listPager = ref({
    page: 1,
    size: 10,
    total: 0,
    max: false,
    loading: false,
    noData: false
})
const orderList = ref<any[]>([])
const getList = async (complete?: Function) => {
    getRentOrders({
        queryStatus: currentStatus.value,
        pageNo: listPager.value.page,
        pageSize: listPager.value.size
    }, {
        complete: complete && complete()
    }).then(res => {

        let list = res.data.data.list
        console.log(list)
        try {
            list.forEach((item: any) => {
                item.statusName = orderStatus.value.find(i => i.value == item.FOrderStatus)?.label || ''
                item.itemStr = JSON.parse(item.itemStr) || []
                item.proInfo = item.itemStr.find((i: any) => i.FItemType == 'B') || {}
                item.renZhenInfo = item.itemStr.find((i: any) => i.FItemType == 'A') || {}
                item.isRentEnd = item.FRentEndDate ? new Date(item.FRentEndDate.replace('-', '/')) < new Date() : false
                item.planList = JSON.parse(item.planStr) || []
                item.planInfo = {
                    // current: item.planList.findIndex((i: any) => new Date(i.debitDate.replace('-', '/')) > new Date()),
                    total: item.planList.length,
                    payed: item.planList.filter((i: any) => i.FDebitStatus == '01').length,
                }
                if(item.applyFinishStatus) {
                    let applyFinishJson = JSON.parse(item.applyFinishStatus)
                    if(applyFinishJson && applyFinishJson[0]) {
                        item.applyStatus = applyFinishJson[0].FApplyStatus
                        item.applyRemark = applyFinishJson[0].FApplyRemark
                        item.checkRemark = applyFinishJson[0].FCheckRemark
                    }
                }
            })
        } catch (error) {
            console.log(error)
        }
        console.log(list)
        if(listPager.value.page == 1) {
            orderList.value = list
        } else {
            orderList.value = orderList.value.concat(list)
        }
        listPager.value.noData = res.data.data.total == '0'
        listPager.value.max = +res.data.data.total <= orderList.value.length
    })

}

const onRefresh = (complete?: Function) => {
    console.log(111111)
    listPager.value.loading = true
    listPager.value.max = false
    listPager.value.noData = false
    listPager.value.page = 1
    orderList.value = []
    getList(() => {
        listPager.value.loading = false;
        complete && typeof complete == 'function' && complete()
    })

}

const onInfinite = () => {
    if (listPager.value.loading || listPager.value.max) return
    listPager.value.loading = true
    listPager.value.page += 1
    getList(() => {
        listPager.value.loading = false
    })

}


// 订单详情
const goDetail = (item: any) => {
    uni.navigateTo({
        url: `/pages/order/detail?orderNo=${item.FOrderNo}`
    })
}
// 支付订单
const payOrder = (item: any) => {
    uni.navigateTo({
        url: `/pages/order/pay?orderNo=${item.FOrderNo}`
    })
    Store.commit('shop/SET_TEMP_STORE_NO', item.FStoreNo);

}

const toYajinList = (item: any) => {
    uni.navigateTo({
        url: `/pages/order/yajinList?orderNo=${item.FOrderNo}`
    })
}

// 取消订单
const handleCancelOrder = async (item: any) => {
    let action = await interact.modal({
        title: '提示',
        message: '确认取消该订单吗？',
        showCancel: true,
    })
    if(action.cancel) return;
    cancelOrder({
        orderNo: item.FOrderNo
    }).then(res => {
        onRefresh()
    })
}

const copyOrderNo = (orderNo: string) => {
    uni.setClipboardData({
        data: orderNo,
        success: function () {
            uni.showToast({
                title: '复制成功',
                icon: 'success',
                duration: 2000
            })
        }
    })
}


const callService = () => {
    console.log(concatPhone.value);
    uni.makePhoneCall({
        phoneNumber: concatPhone.value
    })
}


const popupEditRef = ref<InstanceType<typeof popupEdit>>()
const applyFinish = (item: any) => {
    console.log(popupEditRef.value, item);
    popupEditRef.value.open({
        required: true,
        title: '申请退租',
        placeholder: '请输入退租原因',
    }).then(rst => {
        applyFinishRent({
            applyRemark: rst,
            orderNo: item.FOrderNo
        }).then(res => {
            // interact.toast('已提交')
            showKefuWeixinDialog('提交成功，扫码添加客服微信')
            onRefresh()
        })
    })
}

const kefuWeixinDialogRef = ref(null)
const kefuDialogTitle = ref('')
const showKefuWeixinDialog = (title) => {
    kefuDialogTitle.value = title
    kefuWeixinDialogRef.value.open()
}

const callKefuPhone = () => {
    uni.makePhoneCall({
        phoneNumber: concatPhone.value
    })
}

</script>

<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background-color: #f8f8f8;
}

.order-nav {
    background: #fff;
    border-bottom: 1rpx solid #eee;
    position: sticky;
    top: 0;
    z-index: 999;

    .scroll-view {
        width: 100%;
        white-space: nowrap;
        padding: 20rpx 0;
    }

    .nav-item {
        display: inline-block;
        padding: 15rpx;
        margin: 0 10rpx;
        font-size: 28rpx;
        color: #333;
        position: relative;

        &.active {
            color: $baseColor;
            font-weight: bold;

            &::after {
                content: '';
                position: absolute;
                bottom: -10rpx;
                left: 50%;
                transform: translateX(-50%);
                width: 40rpx;
                height: 4rpx;
                background: $baseColor;
                border-radius: 2rpx;
            }
        }
    }
}

.order-list {
    padding: 20rpx;
}

.order-item {
    background: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    .order_no{
        padding: 20rpx 20rpx 0;
        text{
            color: #ff6600;
            margin-left: 10rpx;
        }
    }

    .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        border-bottom: 1rpx solid #eee;

        .store-info {
            display: flex;
            align-items: center;

            .store-name {
                // margin-left: 10rpx;
                font-size: 28rpx;
            }
        }

        .order-status {
            color: $baseColor;
            font-size: 26rpx;
        }
    }

    .order-content {
        display: flex;
        padding: 20rpx;

        .product-img {
            width: 160rpx;
            height: 160rpx;
            border-radius: 8rpx;
        }

        .order-info {
            flex: 1;
            margin-left: 20rpx;

            .product-name {
                font-size: 28rpx;
                color: #333;
                font-weight: bold;
            }

            .product-specs {
                font-size: 26rpx;
                color: #999;
                margin: 16rpx 0;
            }

            .price-info {
                margin: 16rpx 0;
                // display: flex;
                // justify-content: space-between;


                .price {
                    color: $baseColor;
                    font-size: 30rpx;
                    font-weight: bold;
                }

                .count {
                    color: #999;
                    font-size: 26rpx;
                }
            }
        }
    }

    .order-footer {
        padding: 20rpx;
        border-top: 1rpx solid #eee;

        .total {
            text-align: right;
            font-size: 26rpx;
            color: #666;

            .total-price {
                color: $baseColor;
                font-weight: bold;

            }
            .yj_btn{
                color: #fa6262;
                font-size: 26rpx;
                border: 1rpx solid #fa6262;
                border-radius: 30rpx;
                padding: 0 20rpx;
                height: 50rpx;
                line-height: 50rpx;
            }
        }

        .btn-group {
            display: flex;
            justify-content: flex-end;
            margin-top: 20rpx;

            .btn {
                padding: 0 30rpx;
                height: 60rpx;
                line-height: 60rpx;
                font-size: 26rpx;
                margin-left: 20rpx;
                border-radius: 30rpx;

                &.btn-cancel {
                    color: #666;
                    background: #f5f5f5;
                }

                &.btn-primary {
                    color: #fff;
                    background: $baseColor;
                }

                &.call_phone{
                    color: #fff;
                    background-color: #fa6262;
                    margin-left: auto;
                }

                &.btn-danger {
                    color: #fff;
                    background: #ff8c8c;
                }

                &.btn-default {
                    color: $baseColor;
                    border: 1rpx solid $baseColor;
                    background: #fff;
                }
            }
            .finish_remark{
                line-height: 60rpx;
                color: red;
                max-width: 400rpx;
                @include overflow();

            }
        }
    }
}

.empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 200rpx;

    image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 20rpx;
    }

    text {
        color: #999;
        font-size: 28rpx;
    }
}

.kefu_weixin_dialog{
    width: 600rpx;
    background-color: #fff;
    .title {
        font-size: 30rpx;
        font-weight: bold;
        text-align: center;
        line-height: 40rpx;
        padding-top: 30rpx;
    }
    .img{
        width: 100%;
        image{
            width: 100%;
        }
    }
    .call_phone{
        font-size: 30rpx;
        color: #333;
        text-align: center;
        line-height: 80rpx;
        border-top: 1rpx solid #eee;
        padding-bottom: 30rpx;
        text{
            color: #409eff;
            font-weight: bold;
        }
    }
}
</style>
